<!-- 添加收货地址 -->
<template>
	<view class="page">
		<view class="container">
			<view class="list">
				<view class="list-item">
					<text class="label">收货人：</text>
					<input class="input" type="text" v-model="formData.name" placeholder="请填写收货人姓名"
						placeholder-style="color: #999;" />
					<view class="radio-group">
						<view class="radio-label" @click="handleSexChange(1)">
							<text class="radio iconfont" :class="{'active': formData.sex == 1}">
								{{formData.sex == 1 ? '&#xe62c;': '&#xe6a6;'}}
							</text>
							<text class="text">先生</text>
						</view>
						<view class="radio-label" @click="handleSexChange(2)">
							<text class="radio iconfont" :class="{'active': formData.sex == 2}">
								{{formData.sex == 2 ? '&#xe62c;': '&#xe6a6;'}}
							</text>
							<text class="text">女士</text>
						</view>
					</view>
				</view>
				<view class="list-item">
					<text class="label">手机号：</text>
					<input type="tel" v-model="formData.phone" placeholder="请填写收货人手机号"
						placeholder-style="color: #999;" />
				</view>
			</view>

			<view class="list">
				<view class="list-item">
					<text class="label">所在地区：</text>
					<picker class="picker" mode="multiSelector" :range="regionRange" range-key="name"
						:value="regionValue" @columnchange="handleRegionColumnChange" @change="handleRegionChange">
						<view class="picker-label placeholder" v-if="!regionName.length">请选择省、市、区</view>
						<view class="picker-label" v-else>{{regionName[0]}}，{{regionName[1]}}，{{regionName[2]}}</view>
					</picker>
					<!-- 按钮 -->
					<button class="location-btn btn-transition-scale9" @click.stop="handleNavToLocationPage()">
						<image class="icon" src="/pagesC-shopping/static/images/location.svg" mode="widthFix"></image>
						<text class="text">定位</text>
					</button>
				</view>
				<view class="list-item">
					<text class="label">详细地址：</text>
					<input class="input" type="text" v-model="formData.address" placeholder="请输入详细地址"
						placeholder-style="color: #999;" />
				</view>
				<view class="list-default-address">
					<text class="label">设为默认地址：</text>
					<view class="tips-box">
						<text class="tips">提示：下单时会优先使用该地址</text>
						<text class="checkbox iconfont" :class="{'active': formData.is_default == 1}"
							@click="handleDefaultAdderssChange()">
							{{formData.is_default == 1 ? '&#xe648;': '&#xe751;'}}
						</text>
					</view>
				</view>
				<view class="tags-add">
					<text class="label">地址标签：</text>
					<button class="add-tag btn-transition-scale9" @click="handleAddTag()">添加标签</button>
					<button class="manage-tag btn-transition-scale9"
						@click="handleManageTag()">{{isManageTag ? '完成管理': '管理标签'}}</button>
				</view>
				<view class="tag-group">
					<view class="tag" v-for="item in tags" :key="item.id"
						:class="{'active': item.id == formData.tag_id}" @click="handleChooseTag(item)">
						{{item.name}}
						<button v-show="isManageTag" @click="handleDeleteTag(item)"
							class="close-btn iconfont">&#xe603;</button>
					</view>
				</view>
			</view>
		</view>

		<c-fixed-bottom height="88rpx" extra-bottom-distance="40rpx">
			<view class="btn-box">
				<button class="submit-btn btn-transition-scale95" @click="handleSubmit()">保存收货地址</button>
			</view>
		</c-fixed-bottom>
	</view>
</template>

<script setup>
	import api from "@/api/index.js";
	import { ref, toValue, getCurrentInstance, onMounted } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { validate_telephone } from '@/utils/utils.js';
	import location from './location.js';

	const tags = ref([]);
	const isManageTag = ref(false);
	// 表单字段
	const formData = ref({
		id: '',
		name: '', // 联系人姓名
		sex: '0', // 联系人性别 0-未知 1-男(先生) 2-女(女士)
		phone: '', // 联系电话
		is_default: '0', // 是否默认地址(1=是,0=否)
		tag_id: '', // 地址标签id
		province_id: '', // 省份id
		city_id: '', // 城市id
		district_id: '', // 区id
		address: '', // 详细地址
	});
	// 校验规则
	const rules = [
		{ field: 'name', message: '请填写收货人姓名' },
		{ field: 'phone', message: '请填写收货人手机号', validator: validate_telephone, errorMsg: '请输入正确的手机号' },
		{ field: 'province_id', message: '请选择省份' },
		{ field: 'city_id', message: '请选择城市' },
		{ field: 'area_id', message: '请选择区县' },
		{ field: 'address', message: '请输入详细地址' },
	];

	// 省/市/区/详细地址相关
	const {
		regionRange,
		regionValue,
		regionName,
		handleRegionColumnChange,
		handleRegionChange,
		handleNavToLocationPage,
		handleDisplay
	} =
	location(formData);

	// onMounted(() => {
	// 	console.log(getCurrentInstance().getOpenerEventChannel())
	// })

	onLoad((options) => {
		if (options.id) {
			formData.value.id = options.id;
			uni.setNavigationBarTitle({
				title: '修改收货地址'
			});
			// 接收编辑的地址数据
			const eventChannel = getCurrentInstance().proxy.getOpenerEventChannel();
			eventChannel.on('acceptDataFromOpenerPage', (data) => {
				handleReceiveData(data.data); // 处理接收到的数据
			});
		}
		getTags();
	});

	// 处理接收到的数据
	const handleReceiveData = (data) => {
		for (let key in formData.value) {
			if (typeof data[key] === 'number') {
				formData.value[key] = data[key] + '';
			} else {
				formData.value[key] = data[key];
			}
		}
		// 处理区域显示
		handleDisplay();
	}

	// 切换性别选择
	const handleSexChange = (value) => {
		formData.value.sex = value;
	}

	// 是否默认地址
	const handleDefaultAdderssChange = () => {
		formData.value.is_default = formData.value.is_default == '0' ? '1' : '0';
	}

	// 获取标签数据
	const getTags = async () => {
		const res = await api.c_address_api.getTags();
		tags.value = res.data.data;
	}

	// 添加标签
	const handleAddTag = () => {
		uni.showModal({
			title: '标签名称',
			editable: true,
			success: async (res) => {
				if (!res.confirm || !res.content) return;
				if (tags.value.some(item => item.name === res.content))
					return uni.showNoneToast('已存在相同的标签');
				await api.c_address_api.addTag({ name: res.content });
				uni.showSuccessToast('添加成功');
				getTags();
			}
		})
	}

	// 选择标签
	const handleChooseTag = (item) => {
		if (isManageTag.value) return;
		formData.value.tag_id = formData.value.tag_id === item.id ? '' : item.id;
	}

	// 管理标签
	const handleManageTag = () => {
		isManageTag.value = !isManageTag.value;
	}

	// 删除标签
	const handleDeleteTag = (item) => {
		uni.showModal({
			title: '提示',
			content: `您确定要删除“${item.name}”这个标签吗?`,
			success: async (res) => {
				if (!res.confirm) return;
				await api.c_address_api.delTag({ id: item.id });
				uni.showSuccessToast('删除成功');
				getTags();
			}
		})
	}

	// 提交数据
	const handleSubmit = async () => {
		const form = toValue(formData);

		// 校验是否有效
		const valid = rules.every(item => {
			if (!form.hasOwnProperty(item.field)) return true; // 如果表单没有这个字段则跳过
			if (!form[item.field]) {
				uni.showNoneToast(item.message);
				return false;
			}
			if (item.validator) {
				return item.validator(form[item.field], item.errorMsg);
			}
			return true;
		});
		if (!valid) return;

		uni.showLoading({ title: '保存中...', mask: true });
		const post_api = form.id ? api.c_address_api.edit : api.c_address_api.add;
		await post_api(form).finally(() => setTimeout(uni.hideLoading, 100));

		uni.$emit('refresh-address-manage-page'); // 刷新地址列表

		uni.showSuccessToast('保存成功', () => {
			uni.navigateBack();
		});
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 22rpx 25rpx;

		.list {
			border-radius: 20rpx;
			background-color: white;
			padding-left: 30rpx;

			&+.list {
				margin-top: 22rpx;
			}

			&-item {
				display: flex;
				align-items: center;
				height: 100rpx;
				padding-right: 30rpx;

				&+.list-item {
					border-top: 1rpx solid #E5E5E5;
				}

				&.show-right-icon {
					position: relative;

					&::after {
						position: absolute;
						right: 20rpx;
						top: 50%;
						transform: translateY(-50%);
						display: block;
						content: '\e601';
						font-family: 'iconfont';
						font-size: 20rpx;
						color: #222;
					}
				}

				.label {
					flex-shrink: 0;
					font-size: 30rpx;
					color: #222222;
				}

				.input {
					flex-grow: 1;
					padding-right: 20rpx;
				}

				.radio-group {
					flex-shrink: 0;
					display: flex;

					.radio-label {
						display: flex;
						align-items: center;
					}

					.radio-label+.radio-label {
						margin-left: 20rpx;
					}

					.radio {
						font-size: 40rpx;
						color: #DCDCDC;

						&.active {
							color: #FE3333;
						}
					}

					.text {
						font-size: 30rpx;
						color: #222222;
						margin-left: 10rpx;
					}
				}

				.picker {
					flex-grow: 1;
					width: 0;
				}

				.picker-label {
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;

					&.placeholder {
						color: #999;
					}
				}

				.location-btn {
					display: flex;
					flex-direction: column;
					align-items: center;
					background-color: transparent;
					margin-left: 10rpx;

					.icon {
						width: 32rpx;
					}

					.text {
						font-size: 20rpx;
					}
				}
			}

			&-default-address {
				display: flex;
				flex-direction: column;
				justify-content: center;
				height: 140rpx;
				border-top: 1rpx solid #E5E5E5;
				padding-right: 20rpx;

				.label {
					flex-shrink: 0;
					font-size: 30rpx;
					color: #222222;
				}

				.tips-box {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.tips {
						font-size: 22rpx;
						color: #999;
					}

					.checkbox {
						font-size: 40rpx;
						color: #DCDCDC;

						&.active {
							color: #FE3333;
						}
					}
				}
			}

			.tags-add {
				display: flex;
				align-items: center;
				padding-right: 30rpx;
				padding-bottom: 20rpx;
				margin-top: 20rpx;

				.label {
					flex-grow: 1;
					font-size: 30rpx;
					color: #222222;
				}

				.add-tag {
					flex-shrink: 0;
					height: 54rpx;
					font-size: 24rpx;
					color: #FE3333;
					line-height: 54rpx;
					background: #F9DEDE;
					border-radius: 30rpx;
					padding: 0 30rpx;
				}

				.manage-tag {
					flex-shrink: 0;
					height: 54rpx;
					font-size: 24rpx;
					color: #666;
					line-height: 54rpx;
					background: transparent;
					border-radius: 30rpx;
					padding: 0 30rpx;
					margin-left: 20rpx;

					&::after {
						display: block;
						border: 1px solid #e5e5e5;
						border-radius: 100px;
					}
				}
			}

			.tag-group {
				display: flex;
				flex-wrap: wrap;
				padding-bottom: 50rpx;

				.tag {
					position: relative;
					position: relative;
					height: 54rpx;
					font-size: 24rpx;
					color: #222;
					line-height: 54rpx;
					background: #F2F2F4;
					border-radius: 30rpx;
					padding: 0 30rpx;
					margin-top: 30rpx;
					margin-right: 30rpx;
					background-color: #EDEDED;

					&.active {
						color: white;
						background-color: #FE3333;
					}

					.close-btn {
						position: absolute;
						top: -10rpx;
						right: -10rpx;
						font-size: 30rpx;
						color: #D9D9D9;
						border-radius: 50%;
						background: radial-gradient(#999999 50%, transparent 50%);
					}
				}
			}
		}

	}

	.btn-box {
		padding: 0 45rpx;

		.submit-btn {
			width: 100%;
			height: 88rpx;
			font-size: 28rpx;
			color: white;
			text-align: center;
			line-height: 88rpx;
			border-radius: 44rpx;
			background-color: #FE3333;
		}
	}
</style>